import re
from datetime import datetime, timedelta

from django.contrib import messages
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.shortcuts import render, redirect
from django.template.defaultfilters import truncatechars
from django.urls import reverse
from django.utils.html import escapejs

from .models import *

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import CharField, TextField, Q, Count, Sum
from django.db.models.functions import Cast
from django.template.loader import render_to_string

import json
import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone

from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import get_object_or_404, render
from django.http import JsonResponse
from django.db import models
from django.core.paginator import Paginator

# DeepSeek API配置
AI_API_URL = "https://api.deepseek.com/v1/chat/completions"
AI_API_KEY = "sk-3225ea9f7a294697b4228afb5237b739"  # 替换为您的实际API密钥
DEEPSEEK_MODEL = "deepseek-chat"  # 正确的模型名称


# Create your views here.
def login(request):
    if request.method == 'GET':
        user = Customer.objects.filter(username='root').first()
        user.set_password('root')
        user.save()
        return render(request, 'login.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        if bool(re.match(pattern, username)):
            user = Customer.objects.filter(email=username).first()
        else:
            user = Customer.objects.filter(username=username).first()
        if user:
            if user.status == '启用':
                if user.check_password(password):
                    auth_login(request, user)
                    return redirect(reverse('store_system:index'))
                else:
                    error = "密码错误！"
            else:
                error = "用户已禁用！"
        else:
            error = "用户名或邮箱错误！"
        return render(request, 'login.html', {'error': error})


def about(request):
    """关于我们页面"""
    if request.method == 'POST':
        # 检查是否是AJAX请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            # 处理AJAX表单提交
            user_name = request.POST.get('name')
            email = request.POST.get('email')
            content = request.POST.get('message')

            # 验证表单数据
            if not all([user_name, email, content]):
                return JsonResponse({
                    'success': False,
                    'message': '请填写所有必填字段'
                })

            # 保存反馈到数据库
            try:
                UserBack.objects.create(
                    user=user_name,
                    email=email,
                    content=content,
                    date=timezone.now().date()
                )
                return JsonResponse({
                    'success': True,
                    'message': '感谢您的反馈！我们会尽快回复您。'
                })
            except Exception as e:
                return JsonResponse({
                    'success': False,
                    'message': f'提交失败：{str(e)}'
                })
        else:
            # 处理普通表单提交（保持向后兼容）
            user_name = request.POST.get('name')
            email = request.POST.get('email')
            content = request.POST.get('message')

            # 验证表单数据
            if not all([user_name, email, content]):
                messages.error(request, '请填写所有必填字段')
                return render(request, 'about.html')

            # 保存反馈到数据库
            try:
                UserBack.objects.create(
                    user=user_name,
                    email=email,
                    content=content,
                    date=timezone.now().date()
                )
                messages.success(request, '感谢您的反馈！我们会尽快回复您。')
                return redirect('store_system:about')
            except Exception as e:
                messages.error(request, f'提交失败：{str(e)}')
                context = {
                    'form_data': {
                        'name': user_name,
                        'email': email,
                        'message': content
                    }
                }
                return render(request, 'about.html', context)

    # GET请求直接渲染页面
    return render(request, 'about.html')


def community(request):
    seven_day_ago = datetime.now() - timedelta(days=7)
    stories = Store.objects.filter(date__gte=seven_day_ago).annotate(comments_count=Count('comments')).order_by('-read','-likes')[:3]
    authors = Customer.objects.filter(gategory='作者').annotate(stories_count=Count('stores')).annotate(stories_likes_sum=Sum('stores__likes')).order_by('-stories_count', '-stories_likes_sum')[:5]
    comments = Comment.objects.filter(status='已审核').order_by('-date')[:3]

    result = {
        'stories': stories,
        'authors': authors,
        'comments': comments
    }
    return render(request, 'community.html', result)


def library(request):
    # 查询
    stories = Store.objects.filter(status="已审核")
    gategory = request.GET.get('gategory', '').strip()
    search = request.GET.get('search', '').strip()
    sort = request.GET.get('sort', 'newest')
    # page_number = request.GET.get('page', 1)
    category_id = request.GET.get('category', '').strip()
    if category_id and category_id != 'all':
        stories = stories.filter(gategory__id=category_id)
    # 最新排序
    if gategory and gategory != 'all':
        stories = stories.filter(category__id=gategory)
    if search:
        stories_with_str = stories.annotate(
            title_str=Cast('title', CharField()),
            content_str=Cast('content', TextField())
        )
        # 分别筛选标题和内容，再合并（使用同一个查询集避免结构不一致）
        stories = stories_with_str.filter(title_str__icontains=search).union(
            stories_with_str.filter(content_str__icontains=search)
        )
    if sort == 'newest':
        stories = stories.order_by('-date')  # 最新优先（按创建日期降序）
    elif sort == 'hottest':
        stories = stories.order_by('-read')  # 最热优先（按阅读量降序）
    elif sort == 'most_liked':
        stories = stories.order_by('-likes')
    paginator = Paginator(stories, 8)
    try:
        page_number = int(request.GET.get('page', 1))
        # 确保页码不小于1
        page_number = max(1, page_number)
        page = paginator.page(page_number)

    except (ValueError, TypeError):
        # 若转换失败，默认使用第1页
        page = paginator.page(1)
    except EmptyPage:
        # 若页码超出范围，返回最后一页
        page = paginator.page(paginator.num_pages)

    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        stories_html = ''
        for story in page.object_list:
            escaped_content = escapejs(story.content)
            # 处理 truncated_content，这里简单截取前 100 个字符（若需要更复杂的截断逻辑可调整）
            truncated_content = story.content[:100] if len(story.content) > 100 else story.content
            categories = []
            for cat in story.gategory.all():  # 这里使用正确的category字段
                categories.append(cat.name)
            category_display = ', '.join(categories) if categories else '无'
            stories_html += f'''
                <div class="story-card" data-story-id="{story.id}">
                   <div class="story-image">
                       <img src="">
                   </div>
                   <div class="story-info"
                        data-story-title="{story.title}"
                        data-story-author="{story.author.username}"
                        data-story-content="{escaped_content}">
                       <h3>{story.title}</h3>
                       <p class="truncated-content">{truncated_content}</p>
                       <div class="story-meta">
                           <span>作者: {story.author.username}</span> 
                           <span>{category_display}</span>
                           <span class="like-container">
                                <span class="btn" data-story-id="{story.id}" data-liked="false">⭐</span>
                                <span class="like-count"> {story.likes}</span>-
                                <span class="read-count">{story.read}</span>
                           </span>
                       </div>
                   </div>
               </div>
            '''
        # 返回JSON数据
        return JsonResponse({
            'stories_html': stories_html,
            'current_page': page.number,
            'total_pages': paginator.num_pages,
            'has_previous': page.has_previous(),
            'has_next': page.has_next()
        })
    else:
        all_categories = StoreGategory.objects.all()
        comments = Comment.objects.filter(status="已审核")
        return render(request, 'library.html', {
            'page': page,  # 当前页故事数据
            'all_categories': all_categories,
            'comments': comments,
            'current_gategory': gategory,
            'current_search': search,
            'current_sort': sort
        })


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    if request.method == 'POST':
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        confirm_password = request.POST['confirm_password']
        gategory = request.POST['gategory']
        user = Customer.objects.filter(username=username).first()
        user_email = Customer.objects.filter(email=email).first()
        if user:
            error = "用户名已存在！"
        elif user_email:
            error = "邮箱已存在！"
        elif password != confirm_password:
            error = "两次密码输入不正确！"
        else:
            Customer.objects.create_user(username=username, email=email, password=password, gategory=gategory)
            return redirect(reverse('store_system:login'))
    return render(request, 'register.html', {'error': error})


# Create your views here.
def logout(request):
    auth_logout(request)
    return redirect(reverse('store_system:login'))


def index(request):
    if request.user.gategory == '管理员':
        return redirect(reverse('store_system:story_review'))
    else:
        featured_stories = Store.objects.filter(status='已审核').order_by('-likes')[:3]

        # 获取所有分类
        categories = StoreGategory.objects.all()

        context = {
            'featured_stories': featured_stories,
            'categories': categories,
        }
        return render(request, 'index.html', context)


def story_detail(request, story_id):
    try:
        story = Store.objects.get(id=story_id)
        categories = [category.name for category in story.gategory.all()]
        story_data = {
            'id': story.id,
            'title': story.title,
            'content': story.content,
            'author': story.author.username,
            'date': story.date.strftime('%Y-%m-%d'),
            'likes': story.likes,
            'read': story.read,
        }
        return JsonResponse(story_data)
    except Store.DoesNotExist:
        return JsonResponse({'error': '故事不存在'}, status=404)


def get_comments(request):
    story_id = request.GET.get('store_id')
    # 查询该故事的“已审核”评论，返回用户昵称和评论内容
    comments = Comment.objects.filter(
        store__id=story_id,
        status="已审核",
    ).values('id','user__username','content','date')
    return JsonResponse({'comments': list(comments)})


@login_required
@csrf_exempt
def submit_comment(request):
    if request.method == 'POST':
        import json
        data = json.loads(request.body)
        store_id = data.get('store_id')
        content = data.get('content')

        try:
            # 验证故事是否存在
            store = Store.objects.get(id=store_id)
            default_rules = Rules.objects.last()
            # 创建评论（关联当前用户、故事，标记为“未审核”）
            comment = Comment(
                user=request.user,
                store=store,
                content=content,
                status="未审核",
                rules=default_rules
            )
            comment.save()
            return JsonResponse({'success': True})
        except Store.DoesNotExist:
            return JsonResponse({'success': False, 'message': '故事不存在'})
    return JsonResponse({'success': False, 'message': '仅支持POST请求'})


# @login_required
def generate_story(request):
    categories = StoreGategory.objects.all()
    if request.method == 'POST':
        # 获取表单数据
        genre_id = request.POST.get('genre', '')
        category = StoreGategory.objects.filter(id=genre_id).first()

        # 如果没有找到分类，使用第一个分类作为默认值
        if not category and categories:
            category = categories[0]
        keywords = request.POST.get('keywords', '')
        # genre = request.POST.get('genre','科幻')
        length = request.POST.get('length', 'short')

        # 确定字数
        word_count = 500
        if length == 'medium':
            word_count = 1000
        elif length == 'long':
            word_count = 2000

        try:
            # 构建提示词
            prompt = f"""请创作一个{category}类型的故事，关键词：{keywords}。
            故事要求：
            1. 长度大约{word_count}字
            2. 包含完整的起承转合
            3. 语言生动有趣
            4. 标题简洁有力"""

            # 构建请求数据
            data = {
                "model": DEEPSEEK_MODEL,
                "messages": [
                    {"role": "system", "content": "你是一个专业的故事作家，擅长创作各种类型的故事。"},
                    {"role": "user", "content": prompt}
                ],
                "max_tokens": word_count * 2,
                "temperature": 0.8,
                "stream": False
            }

            # 发送请求到DeepSeek API
            headers = {
                "Authorization": f"Bearer {AI_API_KEY}",
                "Content-Type": "application/json"
            }

            response = requests.post(AI_API_URL, headers=headers, json=data, timeout=30)
            response_data = response.json()

            # 检查响应状态
            if response.status_code == 200:
                story_content = response_data['choices'][0]['message']['content']

                # 提取标题并移除第一行
                title = "AI生成的故事"
                lines = story_content.split('\n')
                if lines:
                    first_line = lines[0].strip()
                    if first_line and len(first_line) < 50:
                        title = first_line.replace('#', '').replace('标题', '').replace('：', ':').strip()
                    # 无论是否提取到标题，都移除第一行
                    story_content = '\n'.join(lines[1:]).strip()

                generated_story = {
                    'title': title,
                    'content': story_content,
                    'genre': category.id,
                    'genre_name': category.name,
                    'length': length,
                    'keywords': keywords
                }

                # 处理AJAX请求
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': True,
                        'story': generated_story
                    })

                return render(request, 'generate.html', {
                    'generated_story': generated_story,
                    'keywords': keywords,
                    'genre': category.id,
                    'length': length,
                    'categories': categories
                })

            else:
                # 处理API错误
                error_msg = f"API错误: {response.status_code}"
                if 'error' in response_data:
                    error_msg += f" - {response_data['error'].get('message', '未知错误')}"

                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({
                        'success': False,
                        'message': error_msg
                    })

                return render(request, 'generate.html', {
                    'error': error_msg,
                    'keywords': keywords,
                    'genre': category.id,
                    'length': length,
                    'categories': categories
                })

        except requests.exceptions.Timeout:
            error_msg = "API请求超时，请稍后重试"
        except requests.exceptions.ConnectionError:
            error_msg = "网络连接错误，请检查网络"
        except Exception as e:
            error_msg = f"生成故事时发生错误: {str(e)}"

        # 错误处理
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'success': False,
                'message': error_msg
            })

        return render(request, 'generate.html', {
            'error': error_msg,
            'keywords': keywords or '',
            'genre': category.id,
            'length': length,
            'categories': categories
        })

    # GET请求
    return render(request, 'generate.html', {
        'categories': categories
    })


@csrf_exempt
def save_story(request):
    if request.method == 'POST':
        try:
            # 解析JSON数据
            data = json.loads(request.body)
            title = data.get('title', '未命名故事')
            content = data.get('content', '')
            genre_data = data.get('genre', '')  # 可能是ID或名称
            keywords = data.get('keywords', '')
            story_id = data.get('story_id')  # 新增：支持编辑已有故事

            # 处理已存在故事的更新
            if story_id:
                try:
                    story = Store.objects.get(id=story_id, author=request.user)
                    story.title = title
                    story.content = content
                    story.save()

                    return JsonResponse({
                        'success': True,
                        'message': '故事更新成功',
                        'story_id': story.id
                    })
                except Store.DoesNotExist:
                    return JsonResponse({
                        'success': False,
                        'message': '故事不存在或您没有编辑权限'
                    })

            # 处理genre数据
            category = None
            if genre_data:
                # 先尝试按ID查找
                if isinstance(genre_data, int) or (isinstance(genre_data, str) and genre_data.isdigit()):
                    try:
                        category = StoreGategory.objects.get(id=int(genre_data))
                    except StoreGategory.DoesNotExist:
                        pass

                # 如果按ID没找到，尝试按名称查找
                if not category:
                    try:
                        category = StoreGategory.objects.get(name=genre_data)
                    except StoreGategory.DoesNotExist:
                        # 如果都没找到，创建新分类或使用默认分类
                        category, created = StoreGategory.objects.get_or_create(name=genre_data)
            else:
                # 使用默认分类
                category, created = StoreGategory.objects.get_or_create(name='奇幻')

            # 获取默认规则
            try:
                default_rule = Rules.objects.get(id=2)
            except Rules.DoesNotExist:
                default_rule = Rules.objects.first()
                if not default_rule:
                    default_rule = Rules.objects.create(name="无违规")

            # 创建新故事
            story = Store.objects.create(
                title=title,
                content=content,
                date=timezone.now(),
                status="未审核",
                likes=0,
                read=0,
                author=request.user,
                share=request.user,
                rules=default_rule
            )

            # 添加分类
            story.gategory.add(category)

            return JsonResponse({
                'success': True,
                'message': '故事保存成功',
                'story_id': story.id
            })

        except Exception as e:
            import traceback
            print(f"保存错误详情: {traceback.format_exc()}")
            return JsonResponse({
                'success': False,
                'message': f'保存失败: {str(e)}'
            })

# def admin_index(request):
#     return render(request, 'admin_index.html')


# def story_review(request):
#     return render(request, 'story_review.html')

# def user_control(request):
#     users_orm = Customer.objects.exclude(gategory='管理员')
#     users = []
#     for user in users_orm:
#         users.append({
#             'id': user.id,
#             'name': user.username,
#             'email': user.email,
#             'avatar': user.headimg,
#             'registerDate': user.date_joined,
#             'status': user.status,
#             'role': user.gategory
#         })
#
#     return render(request, 'user_control.html', {'users': users})


def user_control(request):
    users_orm = Customer.objects.exclude(gategory='管理员')
    users_per_page = 6
    paginator = Paginator(users_orm, users_per_page)
    page = request.GET.get('page')

    try:
        users_page = paginator.page(page)
    except PageNotAnInteger:
        users_page = paginator.page(1)
    except EmptyPage:
        users_page = paginator.page(paginator.num_pages)

    # 将当前页的用户对象转换为字典列表
    users = []
    for user in users_page:
        users.append({
            'id': user.id,
            'name': user.username,
            'email': user.email if user.email else '未添加邮箱',
            'avatar': '/static/img/default.jpg',
            'registerDate': user.date_joined,  # 格式化日期
            'status': user.status,
            'role': user.gategory
        })

    # 处理AJAX请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        data = {
            'users': users,
            'has_previous': users_page.has_previous(),
            'has_next': users_page.has_next(),
            'total_pages': paginator.num_pages,  # 修改字段名以匹配前端期望
            'current_page': users_page.number,
        }
        return JsonResponse(data)

    # 普通请求，渲染完整页面
    context = {
        'users': users,
        'page_obj': users_page,
    }
    return render(request, 'user_control.html', context)


@csrf_exempt
def toggle_user_status(request, user_id):
    if request.method == 'POST':
        try:
            # 检查用户权限
            if not request.user.is_authenticated or request.user.gategory != '管理员':
                return JsonResponse({
                    'success': False,
                    'error': '权限不足，只有管理员可以执行此操作'
                })

            user = get_object_or_404(Customer, id=user_id)

            # 防止管理员禁用自己
            if user.id == request.user.id:
                return JsonResponse({
                    'success': False,
                    'error': '不能禁用您自己的账户'
                })

            # 切换用户状态
            user.status = '禁用' if user.status == '启用' else '启用'
            user.save()

            return JsonResponse({
                'success': True,
                'new_status': user.status,
                'message': f'用户状态已成功切换为{user.status}'
            })

        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': f'操作失败: {str(e)}'
            })

    return JsonResponse({
        'success': False,
        'error': '无效的请求方法'
    })


def data_statistics(request):
    users_count = Customer.objects.count()
    authors_count = Customer.objects.filter(gategory='作者').count()
    stories_count = Store.objects.count()
    comments_count = Comment.objects.count()
    stories_read = Store.objects.all().order_by('-read')[:5]
    stories_likes = Store.objects.all().order_by('-likes')[:5]
    stories_comments_count = Store.objects.all().annotate(comments_count=Count('comments')).order_by('-comments_count')[:5]
    author = Customer.objects.filter(gategory='作者').annotate(stories_count=Count('stores')).annotate(stories_likes=Sum('stores__likes')).order_by('-stories_count', '-stories_likes')[:5]
    result = {
        'stories_read': stories_read,
        'stories_likes': stories_likes,
        'stories_comments_count': stories_comments_count,
        'author': author,
        'users_count': users_count,
        'authors_count': authors_count,
        'stories_count': stories_count,
        'comments_count': comments_count,
    }
    return render(request, 'data_statistics.html', result)


def is_admin(user):
    return user.is_authenticated and user.gategory == '管理员'



# 内容审核主页面
@user_passes_test(is_admin)
def story_review(request):
    # 获取URL参数
    tab = request.GET.get('tab', 'pending')

    # 获取所有分类和规则
    categories = StoreGategory.objects.all()
    rules = Rules.objects.all()

    # 待审核内容
    pending_stories = Store.objects.filter(status='未审核')
    pending_comments = Comment.objects.filter(status='未审核')

    # 已审核内容
    reviewed_stories = Store.objects.filter(status='已审核')
    reviewed_comments = Comment.objects.filter(status='已审核')

    # 待审核故事筛选
    pending_story_category = request.GET.get('pending_story_category', '')
    pending_story_search = request.GET.get('pending_story_search', '')

    if pending_story_category:
        pending_stories = pending_stories.filter(gategory__id=pending_story_category)

    if pending_story_search:
        pending_stories = pending_stories.filter(
            models.Q(title__icontains=pending_story_search) |
            models.Q(content__icontains=pending_story_search) |
            models.Q(author__username__icontains=pending_story_search)
        )

    # 待审核评论筛选
    pending_comment_search = request.GET.get('pending_comment_search', '')

    if pending_comment_search:
        pending_comments = pending_comments.filter(
            models.Q(content__icontains=pending_comment_search) |
            models.Q(user__username__icontains=pending_comment_search) |
            models.Q(store__title__icontains=pending_comment_search)
        )

    # 已审核故事筛选
    reviewed_story_category = request.GET.get('reviewed_story_category', '')
    reviewed_story_violation = request.GET.get('reviewed_story_violation', '')
    reviewed_story_search = request.GET.get('reviewed_story_search', '')

    if reviewed_story_category:
        reviewed_stories = reviewed_stories.filter(gategory__id=reviewed_story_category)

    if reviewed_story_violation == 'violation':
        reviewed_stories = reviewed_stories.exclude(rules__id=2)  # 假设id=2是"正常"规则
    elif reviewed_story_violation == 'normal':
        reviewed_stories = reviewed_stories.filter(rules__id=2)

    if reviewed_story_search:
        reviewed_stories = reviewed_stories.filter(
            models.Q(title__icontains=reviewed_story_search) |
            models.Q(content__icontains=reviewed_story_search) |
            models.Q(author__username__icontains=reviewed_story_search)
        )

    # 已审核评论筛选
    reviewed_comment_violation = request.GET.get('reviewed_comment_violation', '')
    reviewed_comment_search = request.GET.get('reviewed_comment_search', '')

    if reviewed_comment_violation == 'violation':
        reviewed_comments = reviewed_comments.exclude(rules__id=2)  # 假设id=2是"正常"规则
    elif reviewed_comment_violation == 'normal':
        reviewed_comments = reviewed_comments.filter(rules__id=2)

    if reviewed_comment_search:
        reviewed_comments = reviewed_comments.filter(
            models.Q(content__icontains=reviewed_comment_search) |
            models.Q(user__username__icontains=reviewed_comment_search) |
            models.Q(store__title__icontains=reviewed_comment_search)
        )

    # 分页
    pending_story_page_number = request.GET.get('pending_story_page', 1)
    pending_comment_page_number = request.GET.get('pending_comment_page', 1)
    reviewed_story_page_number = request.GET.get('reviewed_story_page', 1)
    reviewed_comment_page_number = request.GET.get('reviewed_comment_page', 1)

    pending_story_paginator = Paginator(pending_stories, 5)
    pending_comment_paginator = Paginator(pending_comments, 10)
    reviewed_story_paginator = Paginator(reviewed_stories, 5)
    reviewed_comment_paginator = Paginator(reviewed_comments, 10)

    pending_story_page = pending_story_paginator.get_page(pending_story_page_number)
    pending_comment_page = pending_comment_paginator.get_page(pending_comment_page_number)
    reviewed_story_page = reviewed_story_paginator.get_page(reviewed_story_page_number)
    reviewed_comment_page = reviewed_comment_paginator.get_page(reviewed_comment_page_number)

    context = {
        'tab': tab,
        'pending_story_page': pending_story_page,
        'pending_comment_page': pending_comment_page,
        'reviewed_story_page': reviewed_story_page,
        'reviewed_comment_page': reviewed_comment_page,
        'categories': categories,
        'rules': rules,
        'pending_story_category': pending_story_category,
        'pending_story_search': pending_story_search,
        'pending_comment_search': pending_comment_search,
        'reviewed_story_category': reviewed_story_category,
        'reviewed_story_violation': reviewed_story_violation,
        'reviewed_story_search': reviewed_story_search,
        'reviewed_comment_violation': reviewed_comment_violation,
        'reviewed_comment_search': reviewed_comment_search,
    }

    return render(request, 'story_review.html', context)


# AJAX审核操作
@user_passes_test(is_admin)
def review_action(request):
    if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        item_type = request.POST.get('type')
        item_id = request.POST.get('id')
        action = request.POST.get('action')
        rule_id = request.POST.get('rule_id', None)

        try:
            if item_type == 'story':
                item = get_object_or_404(Store, id=item_id)

                if action == 'approve':
                    item.status = '已审核'
                    item.save()
                    return JsonResponse({'success': True, 'message': '故事审核通过'})

                elif action == 'reject':
                    if rule_id:
                        rule = get_object_or_404(Rules, id=rule_id)
                        item.status = '已审核'
                        item.rules = rule
                        item.save()
                        return JsonResponse({'success': True, 'message': '故事已标记为违规'})
                    else:
                        return JsonResponse({'success': False, 'message': '请选择违规类型'})

                elif action == 'delete':
                    if rule_id:
                        rule = get_object_or_404(Rules, id=rule_id)
                        item.rules = rule
                        item.save()
                    item.delete()
                    return JsonResponse({'success': True, 'message': '故事已删除'})

                elif action == 'revert':
                    item.status = '未审核'
                    item.save()
                    return JsonResponse({'success': True, 'message': '故事已撤回审核状态'})

                elif action == 'remove_violation':
                    # 假设id=2是"正常"规则
                    normal_rule = get_object_or_404(Rules, id=2)
                    item.rules = normal_rule
                    item.save()
                    return JsonResponse({'success': True, 'message': '已移除违规标记'})

            elif item_type == 'comment':
                item = get_object_or_404(Comment, id=item_id)

                if action == 'approve':
                    item.status = '已审核'
                    item.save()
                    return JsonResponse({'success': True, 'message': '评论审核通过'})

                elif action == 'reject':
                    if rule_id:
                        rule = get_object_or_404(Rules, id=rule_id)
                        item.status = '已审核'
                        item.rules = rule
                        item.save()
                        return JsonResponse({'success': True, 'message': '评论已标记为违规'})
                    else:
                        return JsonResponse({'success': False, 'message': '请选择违规类型'})

                elif action == 'delete':
                    if rule_id:
                        rule = get_object_or_404(Rules, id=rule_id)
                        item.rules = rule
                        item.save()
                    item.delete()
                    return JsonResponse({'success': True, 'message': '评论已删除'})

                elif action == 'revert':
                    item.status = '未审核'
                    item.save()
                    return JsonResponse({'success': True, 'message': '评论已撤回审核状态'})

                elif action == 'remove_violation':
                    # 假设id=2是"正常"规则
                    normal_rule = get_object_or_404(Rules, id=2)
                    item.rules = normal_rule
                    item.save()
                    return JsonResponse({'success': True, 'message': '已移除违规标记'})

            return JsonResponse({'success': False, 'message': '无效的操作'})

        except Exception as e:
            return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})

    return JsonResponse({'success': False, 'message': '无效的请求'})


@login_required
def personal_center(request):
    user = request.user

    # 获取用户最近的评论
    user_comments = user.comments.all().order_by('-id')[:10]

    # 获取用户创作的故事
    user_stories = user.stores.all().order_by('-date')[:5]

    # 计算总获赞数
    total_likes = user.stores.aggregate(Sum('likes'))['likes__sum'] or 0

    context = {
        'user': user,
        'user_comments': user_comments,
        'user_stories': user_stories,
        'total_likes': total_likes,
    }

    return render(request, 'personal_center.html', context)


from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render


@login_required
@csrf_protect
def change_password(request):
    # 处理GET请求 - 返回修改密码页面
    if request.method == 'GET':
        return render(request, 'change_password.html')

    # 处理POST请求 - 修改密码
    try:
        # 从表单数据中获取值，而不是JSON
        current_password = request.POST.get('current_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        # 验证数据
        if not all([current_password, new_password, confirm_password]):
            return JsonResponse({'success': False, 'error': '所有字段都必须填写'})

        if new_password != confirm_password:
            return JsonResponse({'success': False, 'error': '两次输入的新密码不匹配'})

        # 验证当前密码是否正确
        if not request.user.check_password(current_password):
            return JsonResponse({'success': False, 'error': '当前密码不正确'})

        # 设置新密码
        request.user.set_password(new_password)
        request.user.save()

        # 更新会话认证哈希，避免用户需要重新登录
        update_session_auth_hash(request, request.user)
        auth_logout(request)
        # return JsonResponse({'success': True})
        return render(request, 'login.html')
    except Exception as e:
        return JsonResponse({'success': False, 'error': '服务器错误: ' + str(e)})


def toggle_like(request):
    if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        try:
            data = json.loads(request.body)
            story_id = data.get('story_id')
            story = Store.objects.get(id=story_id, status="已审核")

            # 增加点赞数
            story.likes += 1
            story.save()

            return JsonResponse({
                'success': True,
                'new_like_count': story.likes
            })
        except Store.DoesNotExist:
            return JsonResponse({'success': False, 'message': '故事不存在'}, status=404)
        except Exception as e:
            return JsonResponse({'success': False, 'message': str(e)}, status=500)
    return JsonResponse({'success': False, 'message': '无效请求'}, status=400)


# 阅读量统计视图
@csrf_protect
def increase_read(request):
    if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        try:
            data = json.loads(request.body)
            story_id = data.get('story_id')
            story = Store.objects.get(id=story_id, status="已审核")

            # 增加阅读数
            story.read += 1
            story.save()

            return JsonResponse({
                'success': True,
                'new_read_count': story.read
            })
        except Store.DoesNotExist:
            return JsonResponse({'success': False, 'message': '故事不存在'}, status=404)
        except Exception as e:
            return JsonResponse({'success': False, 'message': str(e)}, status=500)
    return JsonResponse({'success': False, 'message': '无效请求'}, status=400)
def delete_comment(request):
    if request.method == "POST":
        comment_id = request.POST.get("comment_id")
        try:
            comment = Comment.objects.get(id=comment_id)
            comment.delete()
            return JsonResponse({"success": True, "message": "评论删除成功"})
        except Comment.DoesNotExist:
            return JsonResponse({"success": False, "message": "评论不存在"})
    return JsonResponse({"success": False, "message": "请求方法错误"})


@login_required
def user_feedback(request):
    feedback_list = UserBack.objects.all().order_by('-date')

    # 设置每页显示的数量
    paginator = Paginator(feedback_list, 5)  # 每页显示5条反馈

    page = request.GET.get('page')
    try:
        feedbacks = paginator.page(page)
    except PageNotAnInteger:
        # 如果page参数不是整数，显示第一页
        feedbacks = paginator.page(1)
    except EmptyPage:
        # 如果页数超出范围，显示最后一页
        feedbacks = paginator.page(paginator.num_pages)

    return render(request, 'user_feedback.html', {'feedbacks': feedbacks})
